import network,time
import urequests
import ujson

try:
    with open('config.json', 'r') as f:
        config = ujson.load(f)
        VERSION = config['VERSION']
        WIFI_SSID = config['WIFI_SSID']
        WIFI_PASSWORD = config['WIFI_PASSWORD']
        TARGET_MAC = config['DDMAC']
        SERVER_IP = config['SERVER_IP']
        SERVER_PORT = config['SERVER_PORT']
        SERVER_PATH = config['SERVER_PATH']
        WEB_USERNAME = config['WEB_USERNAME']
        WEB_PASSWORD = config['WEB_PASSWORD']
except (OSError, KeyError, ValueError):
        VERSION = None
        WIFI_SSID = None
        WIFI_PASSWORD = None
        TARGET_MAC = None
        SERVER_IP = None
        SERVER_PORT = None
        SERVER_PATH = None
        WEB_USERNAME = None
        WEB_PASSWORD = None
        print('config file error')


wlan_if=0

print('ver：'+VERSION)

def do_connect():
    add=0

    wlan = network.WLAN(network.STA_IF)
    wlan.active(False)
    time.sleep(1)
    wlan.active(True)

    if not wlan.isconnected():
        print('connecting to network...\n')
        wlan.connect(WIFI_SSID, WIFI_PASSWORD)
        while not wlan.isconnected():
            time.sleep(0.5)
            add+=1
            if add>40:
                wlan_if=1
                print('connect WiFi TIME OUT!\n')
                break

        print('network config:', wlan.ifconfig())
        return True

def modify_json_file(key_to_modify, new_value):
    try:
        with open('config.json', 'r') as file:
            data = ujson.load(file)
        if key_to_modify in data:
            data[key_to_modify] = new_value
        else:
            print(f"key {key_to_modify} not in config")
            return
        with open('config.json', 'w') as file:
            ujson.dump(data, file)
        print("config save...")
    except Exception as e:
        print(f"error: {e}")

#connect WiFi and check if a new version is available         
try:
    do_connect()
    
    url="https://raw.gitcode.com/x2in/esp32ble/raw/main/main.py"
    data=urequests.get(url,).content
    newver=eval(chr(data[5]))*100+eval(chr(data[7]))*10+eval(chr(data[9]))
    newversion=chr(data[5])+'.'+chr(data[7])+'.'+chr(data[9])
    print('newversion:',newversion)
    Oldver=VERSION
    print('Oldversion:',Oldver)
    over=eval(Oldver[0])*100+eval(Oldver[2])*10+eval(Oldver[4]) 
    
    if over<newver:
        print("start update system......")
        with open(r"main.py", "wb") as f:
            f.write(data)
            print("update complete")
            
            modify_json_file('VERSION', newversion)
            print('new version:',newversion)
            
            #reboot system
            #machine.reset()     
            
    else:
        print("No Update")                
except:
    pass

